import { Card, Button, Form, Input, Select, message } from 'antd'
import { useNavigate, useParams } from 'react-router-dom'
import { useEffect } from 'react'
import { reqAddHospitalSet, reqGetHospitalSet,reqUpdateHospitalSet } from '@api/hospital/hospitalSet'

export default function HospitalSetAddOrUpdate() {
  const { id } = useParams()
  const [form] = Form.useForm()
  const navigate = useNavigate()
  const onFinish = async (values: any) => {
    const data = form.getFieldsValue()
    if(id){
      data.id = id
      reqUpdateHospitalSet(data)
      message.success("修改成功")
    }else{
      await reqAddHospitalSet(data)
      message.success('添加成功')
    }
    navigate('/syt/hospital/hospitalSet')
  }

  useEffect(() => {
    async function fetchData() {
      const result = await reqGetHospitalSet(id as string)
      form.setFieldsValue(result)
    }
    id && fetchData()
  }, [])

  return (
    <Card>
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 2 }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[{ required: true, message: '请输入医院名称!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="医院编号"
          name="hoscode"
          rules={[{ required: true, message: '请输入医院编号!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="api基础路径"
          name="apiUrl"
          rules={[{ required: true, message: '请输入api基础路径!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="联系人名称"
          name="contactsName"
          rules={[{ required: true, message: '请输入联系人名称!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="联系人手机"
          name="contactsPhone"
          rules={[
            {
              required: true,
              message: '请输入合法的联系人手机!',
              pattern: /^1[3-9]\d{9}$/,
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 2 }}>
          <Button type="primary" htmlType="submit" style={{ marginRight: 20 }}>
            保存
          </Button>
          <Button onClick={()=>navigate(-1)}>返回</Button>
        </Form.Item>
      </Form>
    </Card>
  )
}
